import { getTag,getTagDeatil,getTagDetailList } from '@/services';
import { ITagDetail, ITag,ITagDetailList } from '@/types';
import { Effect, Reducer } from 'umi';


export interface TagModelState {
  tag: ITag[];
  tagDetailList: Partial<ITagDetailList>;
  tagDetail:ITagDetail[]
}

export interface tagType {
  namespace: 'tag';
  state: TagModelState;
  effects: {
    getTag: Effect;
    getTagDetailList: Effect;
    getTagDetail: Effect;
  };
  reducers: {
    save: Reducer<TagModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<AritcleState>;
  };
}

const tag: tagType = {
  //命名空间 限定模块之间相互影响
  namespace: 'tag',

  //数据模型状态 相当于vuex中的state
  state: {
    tag: [],
    tagDetailList: {},
    tagDetail:[]
  },

  //异步操作 *相当于vuex的action
  effects: {
    //先简单理解 * 相当于async yield相当于await
    //获取tag列表
    *getTag({ payload }, { call, put }) {
      let result = yield call(getTag, payload);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            tag: result.data,
          },
        });
      }
    },
    //tag下详情列表
    *getTagDetailList({ payload }, { call, put }) {
      let result = yield call(getTagDetailList, payload); 
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            tagDetailList: result.data,
          },
        });
      }
    },
    //tag下详情列表
    *getTagDetail({ payload }, { call, put }) {
      let result = yield call(getTagDeatil, payload); 
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            tagDetail: result.data[0],
          },
        });
      }
    },
  },

  //同步操作 相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default tag;
